package com.atguigu.flink.chapter07;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.util.KKutil;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink11_Watermark_Custom {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        //自动水印发射间隔
        env.getConfig().setAutoWatermarkInterval(3000);
        env
                .socketTextStream("hadoop162", 9999)
                .map(line ->{
                    String[] strings = line.split(",");
                    return new WaterSensor(
                            strings[0],
                            Long.valueOf(strings[1]),
                            Integer.valueOf(strings[2]));
                })

                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .forGenerator(new WatermarkGeneratorSupplier<WaterSensor>() {
                            @Override
                            public WatermarkGenerator<WaterSensor> createWatermarkGenerator(Context context) {
                               //自定义延迟策略方法
                                return new MyWaterMarkGenerator();
                            }
                        })
                                .withTimestampAssigner((SerializableTimestampAssigner<WaterSensor>) (element, recordTimestamp) -> element.getTs())
                )


                .keyBy(WaterSensor::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))

                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String value, Context ctx, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                        List<WaterSensor> list = KKutil.toList(elements);
                        out.collect(value+"  "+ elements);

                    }
                })

                .print();


        env.execute();
    }

  public static class MyWaterMarkGenerator implements WatermarkGenerator<WaterSensor>{
        private long maxTimestamp = Long.MIN_VALUE +3000 ;


      @Override
      public void onEvent(WaterSensor event, long eventTimestamp, WatermarkOutput output) {
          System.out.println("MyWaterMarkGenerator.onEvent");

          //每来一条执行一次 没有周期性执行就是打点师的
          maxTimestamp = Math.max(maxTimestamp,eventTimestamp);
      }

      @Override
      public void onPeriodicEmit(WatermarkOutput output) {
          System.out.println("MyWaterMarkGenerator.onPeriodicEmit");
          //每个周期执行一次
          output.emitWatermark(new Watermark(maxTimestamp - 3000));

      }
  }

}
